<template>
  <div>
    <!-- <div class="tabs-top-btns"> -->
      <!-- <a-radio-group value="1">
        <a-radio-button value="1"> 全部用户 </a-radio-button>
      </a-radio-group> -->
      <!-- <div>
        <a-button type="primary"> + 导出 </a-button>
        <a-popconfirm
          title="您确定删除已选中用户吗?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onDels"
        >
          <a-button style="margin-left: 8px">批量删除</a-button>
        </a-popconfirm>

      </div> -->
    <!-- </div> -->
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :rowSelection="rowSelection"
      showPagination="auto"
      :scroll="{ x: 1500 }"
    >
      <span slot="baseinfo" slot-scope="text, record">
        <img style="width: 45px; heigth: 45px; border-radius: 5px; margin-right: 10px" :src="record.avatar_url" />
        <ellipsis :length="20" tooltip>{{ record.nickname }} </ellipsis>
      </span>
      <span slot="saas_clerk" slot-scope="text">
        <a-tag v-if="text == '0'">否</a-tag>
        <a-tag color="blue" v-else>是</a-tag>
      </span>
      <span slot="platform" slot-scope="text">
        <ellipsis v-show="text == '0'" :length="4" tooltip>微信</ellipsis>
        <ellipsis v-show="text == '1'" :length="4" tooltip>支付宝</ellipsis>
        <ellipsis v-show="text == '3'" :length="4" tooltip>手机</ellipsis>
      </span>
      <span slot="time" slot-scope="text, record">
        <span>{{ record.created_at | timeFormat }}</span>
      </span>
      <span slot="make" slot-scope="text, record">
        <span>{{ record.created_at | timeFormat }}</span>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a-button type="link" @click="handleEdit(record)" size="small">查看</a-button>
          <!-- <a-divider type="vertical" />
          <a-button type="link" @click="handleRecharge(record)" size="small">编辑</a-button> -->
          <!-- :trigger="['click']" -->
        </template>
      </span>
    </s-table>
    <!-- <a-modal
      title="编辑用户"
      :width="800"
      :confirm-loading="modalLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      v-model="visible"
      @ok="handleOk"
    >
      <a-form class="user-form" :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="用户名" hasFeedback>
          <a-input
            placeholder="用户名"
            :disabled="true"
            v-decorator="['nickname', { rules: [{ required: true, message: '请填写用户名' }] }]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上级" hasFeedback>
          <select-user
            @userInfo="getInfo"
            dataType="single"
            returnType="id"
            selectType="user"
            :defaultUser="defaultUser"
          >
          </select-user>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员等级">
          <a-select placeholder="请选择等级" :default-value="selectedLevel" @change="handleChange">
            <a-select-option :value="item.name" v-for="(item, index) of roleList" :key="index">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="核销员">
          <a-radio-group :default-value="is_saas_clerk" v-model="is_saas_clerk">
            <a-radio :value="'0'">否</a-radio>
            <a-radio :value="'1'">是</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="加入黑名单">
          <a-radio-group :default-value="blacklistValue" v-model="blacklistValue">
            <a-radio :value="'0'"> 关闭 </a-radio>
            <a-radio :value="'1'"> 开启 </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系方式" hasFeedback>
          <a-input
            placeholder="请填写联系方式"
            v-decorator="[
              'contact_way',
              { rules: [{ pattern: /^[1]([3-9])[0-9]{9}$/, message: '请填写正确的手机号' }] },
            ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="累计佣金" hasFeedback>
          <a-input :disabled="true" placeholder="累计佣金" v-decorator="['total_price']" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="可提现佣金" hasFeedback>
          <a-input placeholder="可提现佣金" v-decorator="['price']" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注" hasFeedback>
          <a-textarea :rows="2" v-decorator="['comments']" />
        </a-form-item>
      </a-form>
    </a-modal> -->
    <!-- <a-modal
      title="操作"
      :width="400"
      :confirm-loading="rechargeModalLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      v-model="rechargeVisible"
      @ok="updateUserRecharge()"
    >
      <a-tabs :default-active-key="1" v-model="activeKey">
        <a-tab-pane tab="积分" key="1">
          <a-radio-group name="dddd" :default-value="'1'" v-model="rechargeTypeValue">
            <a-radio :value="'1'"> 充值 </a-radio>
            <a-radio :value="'2'"> 扣除 </a-radio>
          </a-radio-group>
          <a-input style="margin-top: 10px" v-model="integralRechargevalue" placeholder="充值数" />
        </a-tab-pane>
        <a-tab-pane tab="余额" key="2">
          <a-radio-group name="dddd" :default-value="'1'" v-model="rechargeTypeValue">
            <a-radio :value="'1'"> 充值 </a-radio>
            <a-radio :value="'2'"> 扣除 </a-radio>
          </a-radio-group>
          <a-input style="margin-top: 10px" v-model="moneyRechargevalue" placeholder="充值数" />
          <a-input style="margin-top: 10px" v-model="moneyExplain" placeholder="说明" />
        </a-tab-pane>
      </a-tabs>
    </a-modal> -->
  </div>
</template>

<script>
import SelectUser from '@/components/SelectUser/SelectUser'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import pick from 'lodash.pick'
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getUserList, updateUserInfo, userDels } from '@/api/user'
import { userRecharge } from '@/api/recharge'
const columns = [
  {
    title: 'ID',
    dataIndex: 'id'
  },
  {
    title: '用户信息',
    dataIndex: 'nickname',
    scopedSlots: { customRender: 'baseinfo' },
    width: 200
  },
  {
    title: '推荐人id',
    dataIndex: 'parent_id',
    scopedSlots: { customRender: ' ' },
    width: 100
  },
  {
    title: '会员等级',
    dataIndex: 'l_name'
  },
  {
    title: '手机号',
    dataIndex: 'binding'
  },
 {
  title: '核销员',
   dataIndex: 'is_saas_clerk',
   scopedSlots: { customRender: 'saas_clerk' }
  },
  {
    title: '成交订单',
    dataIndex: 'orderCount',
    sorter: (a, b) => a.orderCount - b.orderCount
  },
  {
    title: '成交金额',
    dataIndex: 'priceTotal',
    sorter: (a, b) => a.priceTotal - b.priceTotal
  },
  {
    title: '积分',
    dataIndex: 'integral',
    sorter: (a, b) => a.integral - b.integral
  },
  {
    title: '余额',
    dataIndex: 'money',
    sorter: (a, b) => a.money - b.money
  },
  {
  title: '活跃值',
    dataIndex: 'active_num',
  },
  {
  title: '个人总和',
    dataIndex: 'self_fl_total',
  },
  {
  title: '个人待返',
    dataIndex: 'self_fl_df',
  },
  {
  title: '个人已返',
    dataIndex: 'self_fl_yf',
  },
  {
  title: '团队总和',
    dataIndex: 'team_fl_total',
	sorter: (a, b) => team_fl_total - team_fl_total
  },
  {
  title: '团队立结',
    dataIndex: 'team_fl_now',
  },
  {
  title: '团队待返',
    dataIndex: 'team_fl_df',
  },
  {
  title: '团队已返',
    dataIndex: 'team_fl_yf',
  },
  {
    title: '备注',
    dataIndex: 'comments',
    
  },
  {
    title: '注册时间',
    dataIndex: 'created_at',
    sorter: (a, b) => a.created_at - b.created_at,
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'UserList',
  components: {
    STable,
    Ellipsis,
    SelectUser
  },
  props: {
    queryParam: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    this.columns = columns
    return {
      defaultUser: null,
      parent_id: null,
      userInfo: [],
      selectDate: null,
      locale: zhCN,
      ranges: {
        一月内: () => [moment().startOf('day').subtract(1, 'month'), moment()],
        昨天: () => [moment().startOf('day').subtract(1, 'days'), moment().endOf('day').subtract(1, 'days')],
        最近一周: () => [moment().startOf('day').subtract(1, 'weeks'), moment()]
      },
      dateFormat: 'YYYY-MM-DD',
      user_id: 0,
      moneyExplain: '',
      // 会员列表
      roleList: [],
      // 选择的会员
      selectedLevel: [],
      integralRechargevalue: 0,
      moneyRechargevalue: 0,
      // create model
      visible: false,
      activeKey: '1',
      rechargeVisible: false,
      confirmLoading: false,
      modalLoading: false,
      rechargeModalLoading: false,
      blacklistValue: '0',
      is_saas_clerk: '0',
      rechargeTypeValue: '1',
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      records: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        console.log('loadData request parameters:', parameter)
        return getUserList(parameter).then((res) => {
          this.roleList = res.data.level
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {},
  created () {},
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    // 点击批量删除
    async onDels () {
      try {
        const res = await userDels({ ids: this.selectedRowKeys })
        if (res.code != 0) throw res
        this.$message.success(res.msg)
        this.$refs.table.refresh()
      } catch (error) {
        this.$message.error(error.msg)
      }
    },
    onBlacklistChange: function (value) {
      console.log(value)
    },
    handleChange: function (value) {
      console.log(value)
      this.selectedLevel = value
    },
    handleEdit (record) {
      console.log(record)
      this.$router.push('/user/manage/user-detail?user_id=' + record.id)
    },
    // handleRecharge (record) {
    //   // this.user_id = record.id
    //   // this.rechargeVisible = true
    //   this.parent_id = record.parent_id
    //   this.defaultUser = record.parent_name
    //   this.user_id = record.id
    //   this.blacklistValue = record.blacklist
    //   this.is_saas_clerk = record.is_saas_clerk
    //   this.visible = true
    //   this.$nextTick(() => {
    //     this.form.setFieldsValue(pick(record, ['nickname', 'total_price', 'contact_way', 'comments', 'price']))
    //   })
    //   this.selectedLevel = record.l_name
    //   this.records = record
    // },
    handleOk (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        const len = this.roleList.length
        for (let i = 0; i < len; i++) {
          if (this.selectedLevel.indexOf(this.roleList[i].name) > -1) {
            values.level = this.roleList[i].level
          }
        }
        values.blacklist = this.blacklistValue
        values.is_saas_clerk = this.is_saas_clerk
        values.id = this.records.id
        values.parent_id = this.parent_id
        this.modalLoading = true
        updateUserInfo(values).then((res) => {
          this.modalLoading = false
          if (res.code !== 0) {
            this.$error({
              content: res.msg
            })
          } else {
            this.$message.success('用户信息更新成功！')
            this.visible = false
            this.$refs.table.refresh()
          }
        })
      })
    },
    updateUserRecharge () {
      var type = this.rechargeTypeValue
      var params = {
        type: this.activeKey,
        recharge_type: type,
        user_id: this.user_id,
        integral: this.integralRechargevalue,
        explain: this.moneyExplain,
        money: this.moneyRechargevalue
      }
      userRecharge(params).then((res) => {
        this.modalLoading = false
        if (res.code !== 0) {
          this.$error({
            content: res.msg
          })
        } else {
          this.$message.success(res.msg)
          this.rechargeVisible = false
          this.$refs.table.refresh()
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.blacklistValue = 0
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        dateStart: moment(new Date()),
        dateEnd: moment(new Date())
      }
    },
    moment,
    // 选中日期事件
    calendarChange (date, dateString) {
      // if (date.length <= 1) {
      //   // 选中开始日期事件，设置结束日期必须大于1天
      //   this.selectDate = date[0].add(1, 'days')
      // } else {
      //   this.selectDate = null
      // }
      this.selectDate = date[0]
    },
    // 选择后的事件
    onChange (date, dateString) {
      this.queryParam.dateStart = dateString[0]
      this.queryParam.dateEnd = dateString[1]
    },
    selectLevelChange (value) {
      const len = this.roleList.length
      for (let i = 0; i < len; i++) {
        if (value.indexOf(this.roleList[i].name) > -1) {
          this.queryParam.level = this.roleList[i].level
        }
      }
    },
    getInfo (val) {
      this.parent_id = val
    }
  }
}
</script>

<style lang="less">
.tabs-top-btns {
  padding-bottom: 24px;
  display: flex;
  justify-content: space-between;
}
</style>
